<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="年月日">
          <el-date-picker
            v-model="searchParam.inventoryDate"
            type="date"
            placeholder="请选择年月日"
            value-format="YYYY-MM-DD"
            @change="getTableList"
          />
        </el-form-item>
        <el-form-item label="料号">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入料号"
            clearable
            @keyup.enter="search"
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="resetMaterial"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="批号">
          <el-input
            v-model="searchParam.batchNumber"
            placeholder="请输入批号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="库位名称">
          <el-input
            v-model="searchParam.binCode"
            placeholder="请输入库位名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="存储地点名称">
          <el-input
            v-model="searchParam.storageLocationName"
            placeholder="请输入存储地点名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <!--<el-form-item label="库存日期">
          <el-date-picker
            v-model="searchParam.inventoryDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getinventoryDate"
          />
        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" @click="inventoryImport">
          <template #icon><i-ep-upload /></template>导入
        </el-button>
        <!--<el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button type="success" @click="excelBoxOpen">导入 </el-button>
        <el-dialog title="U9库存数据数据导入" v-model="excelBox" width="555px">
          <div>
            <el-button
              @click="
                useDownload(
                  '/mes/mesinventorydata/exportTemp',
                  'U9库存数据上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              U9库存数据上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>-->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <!--<el-table-column type="selection" width="55" align="center" />-->
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
        <!-- <el-table-column
          label="料号"
          prop="materialCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="品名"
          prop="materialName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="库存日期"
          prop="inventoryDate"
          min-width="100"
          show-overflow-tooltip
          :formatter="formatDate"
          align="center"
        />
        <el-table-column
          label="库存单位名称"
          prop="quantityUnit"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="批号"
          prop="batchNumber"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="库位名称"
          prop="binCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="存储地点名称"
          prop="storageLocationName"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <!--<el-table-column
          label="库存日期"
          prop="inventoryDate"
          min-width="100"
          show-overflow-tooltip
        />-->
        <!-- <el-table-column
          label="批号生效日期"
          prop="batchEffectiveDate"
          min-width="100"
          show-overflow-tooltip
          :formatter="formatDate"
        />
        <el-table-column
          label="批号失效日期"
          prop="batchExpiryDate"
          min-width="100"
          show-overflow-tooltip
          :formatter="formatDate"
        />
        <el-table-column
          label="现存量(库存单位)"
          prop="quantity"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="库存上限"
          prop="inventoryMax"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="库存下限"
          prop="inventoryMin"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <!--<el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>-->
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesinventorydata-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!-- 导入 -->
    <ImportExcel ref="inventoryImportRef" />
    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table
      ref="uploadErrorRef"
      :errorDataList="errorDataList"
      :promptDataList="promptDataList"
      :paramList="paramList"
      :listWorkOrder="listWorkOrder"
      @changelist="changelist"
    />
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />

    <!-- 列设置 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESINVENTORYDATA",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesinventorydata/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialId: "",
  materialCode: "",
  materialName: "",
  batchNumber: "",
  binCode: "",
  storageLocationName: "",
  inventoryDate: "",
};

const deleteParam = {
  api: "/mes/mesinventorydata/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesinventorydata/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开U9库存数据表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改U9库存数据";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增U9库存数据";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开U9库存数据表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "U9库存数据详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getinventoryDate(data: any) {
  if (data) {
    searchParam.value.inventoryDateStart = data[0];
    searchParam.value.inventoryDateEnd = data[1];
  } else {
    searchParam.value.inventoryDateStart = "";
    searchParam.value.inventoryDateEnd = "";
  }
}

// 导入excel
const uploadApi = "/mes/mesinventorydata/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesinventorydata/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}

// 导入周数据
const inventoryImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
const promptDataList = ref([]);
const listWorkOrder = ref([]);
const paramList = ref({});
async function inventoryImportApiFunc(formdata: FormData, config: any) {
  await request
    .post(
      `/mes/mesinventorydata/upload/${searchParam.value.inventoryDate}`,
      formdata,
      config
    )
    .then((res: any) => {
      console.log(res);
      inventoryImportRef.value.resCode = res.code;
      inventoryImportRef.value.sucessTatol = res.data;
    });
}
const changelist = () => {
  search();
};
const inventoryImport = () => {
  if (!searchParam.value.inventoryDate) {
    ElMessage({
      type: "error",
      message: "请选择年月日！",
    });
    return;
  }
  let newSearchParam = { ...searchParam.value };
  // searchParam.value.inventoryDate = "";
  let params = {
    title: "导入U9库存数据",
    tempApi: "/mes/mesinventorydata/exportTemp", //模板下载
    importApi: inventoryImportApiFunc, // 导入
    getTableList, // 成功后回调
    isShowTemp: true, // 是否显示下载模板
    fileTypes: ".xlsx",
    searchParam: newSearchParam,
  };
  inventoryImportRef.value.acceptParams(params);
};
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    // searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  // searchParam.value.materialId = "";
  searchParam.value.materialCode = "";
};

const tableColumns = reactive([
  {
    prop: "materialCode",
    label: "料号",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "materialName",
    label: "品名",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "inventoryDate",
    label: "库存日期",
    minWidth: 100,
    isShow: true,
    align: "center",
    formatter: formatDate,
  },
  {
    prop: "quantityUnit",
    label: "库存单位名称",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "batchNumber",
    label: "批号",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "binCode",
    label: "库位名称",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "storageLocationName",
    label: "存储地点名称",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "batchEffectiveDate",
    label: "批号生效日期",
    minWidth: 100,
    isShow: true,
    align: "left",
    formatter: formatDate,
  },
  {
    prop: "batchExpiryDate",
    label: "批号失效日期",
    minWidth: 100,
    isShow: true,
    align: "left",
    formatter: formatDate,
  },
  {
    prop: "quantity",
    label: "现存量(库存单位)",
    minWidth: 120,
    isShow: true,
    align: "left",
  },
  {
    prop: "inventoryMax",
    label: "库存上限",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "inventoryMin",
    label: "库存下限",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
]);

const searchColumns = reactive([]);
</script>
